<template>
  <!-- 产品库页面 -->
  <div class="app-container">
    <!-- 顶部查询表单 -->
    <div class="top-query-form">
      <el-form :inline="true" class="query-form"
               :model="queryParams"
               ref="queryFormRef"
               label-width="auto">
        <el-form-item label="产品名称：">
          <el-input v-model="queryParams.name" placeholder="请输入"
                    clearable
                    @keyup.enter="handleQuery"
                    class="!w-180px"/>
        </el-form-item>
        <el-form-item label="英文名称：">
          <el-input v-model="queryParams.nameEn"  placeholder="请输入"
                    clearable
                    @keyup.enter="handleQuery"
                    class="!w-180px"
          />
        </el-form-item>
        <el-form-item label="产品规格：">
          <el-input v-model="queryParams.specs" placeholder="请输入"
                    clearable
                    @keyup.enter="handleQuery"
                    class="!w-180px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 主体内容区域 -->
    <div class="main-content">
      <!-- 左侧树结构 -->
      <div class="sidebar">
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="treeProps"
          node-key="id"
          highlight-current
          @node-click="handleNodeClick"
        >
          <template #default="{ node }">
      <span class="tree-node">
        {{ node.label }}
        <span v-if="node.children?.length" class="child-count">
          ({{ node.children.length }}个子分类)
        </span>
      </span>
          </template>
        </el-tree>
      </div>

      <!-- 右侧表格 -->
      <div class="table-container">
        <el-table :data="productList" border stripe>
          <el-table-column prop="code" label="产品编号" />
          <el-table-column prop="name" label="产品名称" />
          <el-table-column prop="nameEn" label="英文名称" />
          <el-table-column prop="nameLatin" label="拉丁文名称" />
          <el-table-column prop="specs" label="产品规格" />
          <el-table-column prop="shape" label="产品性状" />
          <el-table-column prop="exterior" label="颜色外观" />
          <el-table-column prop="store" label="储存条件" />
        </el-table>

        <div class="pagination-container">
          <el-pagination
            background
            layout="total, prev, pager, next, sizes, jumper"
            :total="total"
            :page-size="queryParams.pageSize"
            :current-page="queryParams.pageNo"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { handleTree, findNodeById, getAllChildrenIds } from '@/utils/tree'
import { BaseProductClassApi, ProdInfoApi } from '@/api/customermanager/custfollow'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'

const { t } = useI18n()
const message = useMessage()

// 树形结构数据
const treeData = ref<any[]>([])
const treeProps = {
  children: 'children',
  label: 'name'
}

// 产品列表数据
const productList = ref<any[]>([])
const loading = ref(false)
const total = ref(0)
const selectedNode = ref<any>(null)
const showLeafNodeTip = ref(false)

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  nameEn: undefined,
  specs: undefined,
  classCode: undefined
})

/** 获取树形分类数据 */
const getTreeData = async () => {
  try {
    const data = await BaseProductClassApi.getBaseProductClassList({})
    data.sort((a, b) => {
      if (a.pid === b.pid) {
        return a.orderId - b.orderId
      }
      return a.pid - b.pid
    })
    treeData.value = handleTree(data, 'id', 'pid')
  } catch (error) {
    console.error('获取分类树失败:', error)
    message.error('获取分类树失败')
  }
}

// 组件脚本部分
const handleNodeClick = async (node: any) => {
  try {
    loading.value = true;

    // 1. 收集所有需要查询的分类ID
    const classCodes = new Set<string>();
    classCodes.add(node.id); // 包含当前节点

    // 如果是父节点，添加所有子节点ID
    if (node.children && node.children.length > 0) {
      const childIds = getAllChildrenIds(node);
      childIds.forEach(id => classCodes.add(id));
    }

    // 2. 设置查询参数
    queryParams.classCode = Array.from(classCodes).join(',');
    queryParams.pageNo = 1; // 重置页码

    // 3. 执行查询
    await getProductList();

  } catch (error) {
    console.error('获取产品失败:', error);
    message.error('获取产品失败');
  } finally {
    loading.value = false;
  }
};

const getProductList = async () => {
  try {
    const res = await ProdInfoApi.getProdInfoPage(queryParams);
    productList.value = res.list || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error('获取产品列表失败:', error);
    message.error('获取产品列表失败');
  }
};


/** 查询方法 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getProductList()
}

/** 重置方法 */
const handleReset = () => {
  queryParams.name = undefined
  queryParams.nameEn = undefined
  queryParams.specs = undefined
  queryParams.classCode = undefined
  showLeafNodeTip.value = false
  handleQuery()
}

// 分页方法
const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  getProductList()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNo = val
  getProductList()
}

/** 初始化 */
onMounted(() => {
  getTreeData()
  getProductList()
})
</script>
<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.top-query-form {
  margin-bottom: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.query-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.query-form .el-form-item {
  margin-bottom: 0;
  flex-shrink: 0;
  white-space: nowrap;
}

.query-form .el-input {
  width: 150px;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
  gap: 20px;
}

.sidebar {
  width: 250px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  background: #fff;
  overflow: auto;
}

.table-container {
  flex: 1;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  overflow: auto;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.category-tree {
  background: transparent;
}

.tree-node {
  display: flex;
  align-items: center;
  font-size: 14px;
}
.child-count {
  color: #888;
  font-size: 0.8em;
  margin-left: 5px;
}
</style>
